package com.utcs.modules.resource.basic.service;

import com.utcs.common.persistence.Page;
import com.utcs.common.security.Digests;
import com.utcs.common.service.BaseService;
import com.utcs.common.utils.Encodes;
import com.utcs.modules.resource.basic.dao.RoleDao;
import com.utcs.modules.resource.basic.dao.UserDao;
import com.utcs.modules.resource.basic.entity.Role;
import com.utcs.modules.resource.basic.entity.User;
import com.utcs.modules.resource.basic.utils.UserUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 系统管理，安全相关实体的管理类,包括用户、角色、菜单.
 * Created by Fly on 2017/5/25.
 */
@Service
public class SystemService extends BaseService  {

    public static final String HASH_ALGORITHM = "SHA-1";
    public static final int HASH_INTERATIONS = 1024;
    public static final int SALT_SIZE = 8;

    @Autowired
    private UserDao userDao;
    @Autowired
    private RoleDao roleDao;
    /**
     * 根据用户名获取用户
     * @param name
     * @return
     */
    public User getUserByName(String name) {
        return UserUtils.getByName(name);
    }

    public Page<User> findUser(Page<User> page, User user) {
        // 设置分页参数
        user.setPage(page);
        // 执行分页查询
        page.setList(userDao.findList(user));
        return page;
    }


    /**
     * 生成安全的密码，生成随机的16位salt并经过1024次 sha-1 hash
     */
    public static String encryptPassword(String plainPassword) {
        String plain = Encodes.unescapeHtml(plainPassword);
        byte[] salt = Digests.generateSalt(SALT_SIZE);
        byte[] hashPassword = Digests.sha1(plain.getBytes(), salt, HASH_INTERATIONS);
        return Encodes.encodeHex(salt)+Encodes.encodeHex(hashPassword);
    }

    /**
     * 验证密码
     * @param plainPassword 明文密码
     * @param password 密文密码
     * @return 验证成功返回true
     */
    public static boolean validatePassword(String plainPassword, String password) {
        String plain = Encodes.unescapeHtml(plainPassword);
        byte[] salt = Encodes.decodeHex(password.substring(0,16));
        byte[] hashPassword = Digests.sha1(plain.getBytes(), salt, HASH_INTERATIONS);
        System.out.println("Encodes.encodeHex(salt):" + Encodes.encodeHex(salt));
        System.out.println("Encodes.encodeHex(hashPassword):" + Encodes.encodeHex(hashPassword));
        return password.equals(Encodes.encodeHex(salt)+Encodes.encodeHex(hashPassword));
    }


    public static void main(String[] args) {
        System.out.println(encryptPassword("123456"));

        System.out.println(validatePassword("123456","02665d532e91d809f338622d09e32ac26f5478051b9cbb2a731f4a82"));
    }
}
